import Vue from 'vue'
import Router from 'vue-router'
import store from './store'


Vue.use(Router);

const router=new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      name:'firstPage',
      redirect:'/mainPage/login',
    },
    {
      path:'/mainPage',
      name:'mainPage',
      component:()=>import('./views/mainPage.vue'),
      children:[
        {
          path: 'register',
          name: 'register',
          component: ()=> import('./views/register.vue')
        },
        {
          path: 'login',
          name: 'login',
          // route level code-splitting
          // this generates a separate chunk (about.[hash].js) for this route
          // which is lazy-loaded when the route is visited.
          component: () => import(/* webpackChunkName: "about" */ './views/login.vue')
        },
      ]

    },
    {
      path: '/botNav',
      name: 'botNav',
      // route level code-splitting
      // this generates a separate chunk (about.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import(/* webpackChunkName: "about" */ './views/botNav.vue'),
      children:[
        {
          path:'home',
          name:'home',
          component:()=>import('./views/home.vue'),
        },
        {
          path:'mall',
          name:'mall',
          component:()=>import('./views/mall.vue'),
          meta:{
            requireAuth:true      //无论是刷新还是路由跳转都要身份验证,
          }
        },
        {
          path:'mine',
          name:'mine',
          component:()=>import('./views/mine.vue'),
          meta:{
            requireAuth:true      //无论是刷新还是路由跳转都要身份验证,
          }
        },
        {
          path:'search',
          name:'search',
          component:()=>import('./views/search.vue'),
        },
        {
          path:'classify',
          name:'classify',
          component:()=>import('./views/classify.vue'),
        },
      ]
    }
  ],

})
router.beforeEach((to, from, next) => {

  //每次路由跳转都要检测token是否存在
   let token= window.sessionStorage.getItem('token',token);

   //并保存在store里面
   store.commit('setToken',token);

   //需要凭证的页面就需要进行验证判断
    if(to.meta.requireAuth){
        if(token){
          next();
        }
        //没有token就返回首页
        else{
          next(
            {
             path:'/',
            query:{redirect:to.fullPath}
            }
          );
        }
    }
    //不管怎样都要放行，否则会卡在这里
    next();
});

export default router

 
